package com.lkm.app_ui.jz.ui.fragment;

import static com.lkm.app_ui.m.fun.DelegatePayTask.PayType;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.jz.bean.GetPayBean;
import com.lkm.app_ui.jz.util.JzUtil;
import com.lkm.app_ui.jz.util.Print;
import com.lkm.app_ui.jz.util.Urls;
import com.lkm.app_ui.jz.util.ZXingUtils;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.FunItem;
import com.lkm.app_ui.m.fun.FunModule;
import com.lkm.app_ui.m.fun.OnPayEvent;
import com.lkm.app_ui.m.vip.VipModule;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.app_ui.view.choiceCard.ChoiceItem;
import com.lkm.app_ui.view.choiceCard.IChoiceItem;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.TaskCollection;
import com.lkm.frame.task2.TaskCollectionCycle;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.entity.PayTo;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

/**
 * 2024年3月22日 10:10:08
 * 把按键27改成微会员支付，按键26改成静态聚合支付。
 */
public class PayFragment01 extends MBaseFragment implements ChoiceCard.ChoiceCardBC {

    public static PayFragment01 lastPayFragment;

    public static PayFragment01 getInstance(@PayType int payType, String url, String orderNum) {
        PayFragment01 f    = lastPayFragment = new PayFragment01();
        Bundle        data = new Bundle();
        data.putInt("payType:i", payType);
        data.putString("vipPayUrl:i", url);
        data.putString("orderNum:i", orderNum);
        f.setArguments(data);
        return f;
    }

    @PayType
    private int    payType   = 0;
    private String vipPayUrl = null;//微会员支付二维码
    private String orderNum  = null;//微会员订单号

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_pay01;
    }


    private FunModule      funModule;
    private TaskCollection taskCollection;

    private OrderEntity orderEntity;//订单数据

    private TextView mPayTitleTv01, mPayTitleTv02, mPayTitleTv03;
    private LinearLayout mPayLayout01, mPayLayout02, mPayLayout03;
    private ImageView mPayIv01, mPayIv02, mPayIv03;

    private ChoiceCard mChoiceCard;

    private static final int Money_keyCode    = 0;//现金支付
    private static final int WVip_keyCode     = 1;//微会员支付
    private static final int Delegate_keyCode = 2;//聚合支付
    private static final int Vip_keyCode      = 3;//会员支付


    private static final int vipOrScanPay_keyCode = 6;//进入会员刷卡模式


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        RunTimeData.lastPayOKvipInfo = null;
        payType = getArguments().getInt("payType:i");
        vipPayUrl = getArguments().getString("vipPayUrl:i");
        orderNum = getArguments().getString("orderNum:i");

        funModule = MyApplication.getInstance().getModuleManager().loadModule(FunModule.class);
        taskCollection = new TaskCollectionCycle(MyApplication.getInstance().getTaskManager2(), holdCycleHelp());


        orderEntity = RunTimeData.orderEntity;

        mPayLayout01 = findViewById(R.id.mPayLayout01);
        mPayLayout02 = findViewById(R.id.mPayLayout02);
        mPayLayout03 = findViewById(R.id.mPayLayout03);

        mPayTitleTv01 = findViewById(R.id.mPayTitleTv01);
        mPayTitleTv02 = findViewById(R.id.mPayTitleTv02);
        mPayTitleTv03 = findViewById(R.id.mPayTitleTv03);

        mPayIv01 = findViewById(R.id.mPayIv01);
        mPayIv02 = findViewById(R.id.mPayIv02);
        mPayIv03 = findViewById(R.id.mPayIv03);

//        ((TextView) findViewById(R.id.tv_totalPrice)).setText("应付：" + SteelardHelp.formatMoney(orderEntity.totalPrice) + "元");

        if (!RunTimeData.steelyardExtData.payOnlineInfo.isDelegatePay && !RunTimeData.steelyardExtData.payOnlineInfo.isVipCardPay) {
            //P.p("Bill-> PayFragment01 -> No_isDelegatePay and No_isVipCardPay");
            RouterUINavigation.getInstance().showPayOutline((BaseFragmentActivity) getActivity());
            RouterUINavigation.getInstance().dismiss(this);
            return;
        }


//        RunTimeData.steelyardExtData.payOnlineInfo.isUsbVipSystem = true;
//        RunTimeData.steelyardExtData.payOnlineInfo.isDelegatePay = true;
//        RunTimeData.steelyardExtData.payOnlineInfo.isVipCardPay = true;


        mChoiceCard = findViewById(R.id.ChoiceCard);
        mChoiceCard.setItemViewHeigth(ViewHelp.getPX(getActivity(), R.dimen.dp100px));


        //执行支付任务操作

        reOnKeyEvent();//监听按键

        if (RunTimeData.isSongjian) {
            //P.p("Bill-> PayFragment01 ->isSongjian");
            RouterUINavigation.getInstance().showPayOutline((BaseFragmentActivity) getActivity());
            RouterUINavigation.getInstance().dismiss(this);
        }


        initDataX();
    }

    private void initDataX() {

        String   yf           = orderEntity.payment_amount;
        String   allp         = SteelardHelp.formatMoney(orderEntity.totalPrice);
        TextView tv_tipsPrice = findViewById(R.id.tv_tipsPrice);
        if (StringHelp.isEmpty(yf)) {
            tv_tipsPrice.setVisibility(View.GONE);
            ((TextView) findViewById(R.id.tv_totalPrice)).setText("应付：" + allp + "元");
        } else {
            ((TextView) findViewById(R.id.tv_totalPrice)).setText("应付：" + yf + "元");
            tv_tipsPrice.setVisibility(View.VISIBLE);
            tv_tipsPrice.setText("总价:" + allp + "元");
        }
        //ImageView     qrIv     = findViewById(R.id.img_qr);
        List<FunItem>                funItems = new ArrayList<>();
        List<PayTo.PayOutlineItemTo> payList  = RunTimeData.steelyardExtData.payOutLineInfo.payOutlineItems;
        mPayLayout01.setVisibility(View.GONE);
        mPayLayout02.setVisibility(View.GONE);
        mPayLayout03.setVisibility(View.GONE);

        switch (RunTimeData.tmpPayType) {
            case DelegatePayTask.PayType_StaticDelegate:
                mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item_fun_p, R.layout.item_fun, 2);
                mChoiceCard.setChoiceCardBC(this);

                switch (payList.size()) {
                    case 1:
                        mPayLayout01.setVisibility(View.VISIBLE);
                        mPayLayout02.setVisibility(View.GONE);
                        mPayLayout03.setVisibility(View.GONE);
                        setPayInfoUi(mPayTitleTv01, mPayIv01, payList.get(0));
                        break;
                    case 2:
                        mPayLayout01.setVisibility(View.VISIBLE);
                        mPayLayout02.setVisibility(View.VISIBLE);
                        mPayLayout03.setVisibility(View.GONE);
                        setPayInfoUi(mPayTitleTv01, mPayIv01, payList.get(0));
                        setPayInfoUi(mPayTitleTv02, mPayIv02, payList.get(1));
                        break;
                    case 3:
                        mPayLayout01.setVisibility(View.VISIBLE);
                        mPayLayout02.setVisibility(View.VISIBLE);
                        mPayLayout03.setVisibility(View.VISIBLE);
                        setPayInfoUi(mPayTitleTv01, mPayIv01, payList.get(0));
                        setPayInfoUi(mPayTitleTv02, mPayIv02, payList.get(1));
                        setPayInfoUi(mPayTitleTv03, mPayIv03, payList.get(2));
                        break;
                }
                funItems.add(new FunItem("0", "0：确认收款查看溯源码"));
                funItems.add(new FunItem("9", "9：退出"));
                break;
            case DelegatePayTask.PayType_WVip:
                mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item_fun_p, R.layout.item_fun, 1);

                mChoiceCard.setChoiceCardBC(this);
                mPayLayout01.setVisibility(View.VISIBLE);
                mPayLayout02.setVisibility(View.GONE);
                mPayLayout03.setVisibility(View.GONE);

                mPayTitleTv01.setText("会员支付");
                mPayIv01.setImageBitmap(ZXingUtils.createQRCodeBitmap(vipPayUrl, 400,
                        "UTF-8", "H", "0", Color.BLACK,
                        Color.WHITE, null, null, 0.2f));
                funItems.add(new FunItem("9", "9：退出"));
                //这里启动轮询支付结果。
                pollingResult();
                break;
        }
        ChoiceItem[] cis = new ChoiceItem[funItems.size()];
        int          i   = 0;
        for (FunItem funItem : funItems) {
            cis[i] = new ChoiceItem(funItem.id, funItem.name);
            cis[i].setTag(funItem);
            cis[i].setIsChoice(funItem.isChoice);
            i++;
        }
        mChoiceCard.binData(cis);
    }

    //设置支付标题、Url
    private void setPayInfoUi(TextView titleTv, ImageView payIv, PayTo.PayOutlineItemTo payBean) {
        titleTv.setText(payBean.title);
        if (payBean.url == null || payBean.url.isEmpty()) {
            payIv.setImageResource(R.mipmap.ic_pay_default);
        } else {
            Bitmap bm = null;
            switch (payBean.type) {
                //1、微信；
                case 1:
                    bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_pay_01wx);
                    break;
                //2、支付宝；
                case 2:
                    bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_pay_01ali);
                    break;
                // 3、聚合
                case 3:
                    bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_pay_01jh);
                    break;
            }
            payIv.setImageBitmap(ZXingUtils.createQRCodeBitmap(payBean.url, 400,
                    "UTF-8", "H", "0", Color.BLACK,
                    Color.WHITE, null, bm, 0.2f));
        }
    }

    private Disposable                mResultDisposable;
    private ObservableEmitter<String> resultEmitter;

    @SuppressLint("CheckResult")
    private void pollingResult() {
        //RunTimeData.steelyardInfo.getSteelyardMac()
        mResultDisposable =
                Observable.create((ObservableOnSubscribe<String>) e -> {
                    resultEmitter = e;
                    try {
                        HashMap<String, String> params = new HashMap<>();
                        params.put("act", "server_get_pay_status");
                        params.put("oid", "" + RunTimeData.steelyardInfo.getOrg());
                        params.put("od", orderNum);
                        params.put("ukey", RunTimeData.orderEntity.steelyardMac);
                        params.put("sign", orderEntity.steelyardMac);
                        OkGo.<String>post(Urls.getHost())
                                .params(params)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        GetPayBean getPayBean;
                                        try {
                                            getPayBean = JzUtil.mGson.fromJson(response.body(), GetPayBean.class);
                                        } catch (Exception exception) {
                                            Print.showToast("支付结果查询失败" + exception);
                                            getPayBean = null;
                                        }
                                        GetPayBean data = null;
                                        if (getPayBean != null) data = getPayBean.data;
                                        if (getPayBean != null && 1 == getPayBean.res && data != null && data.type == 2) {
                                            //这里直接跳转溯源
                                            resultEmitter.onNext("ok");
                                            RunTimeData.orderEntity.payTypeName = "会员支付";
                                            go2Trace(false);
                                        } else {
                                            resultEmitter.onComplete();
                                        }
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        Print.showToast("支付结果查询失败" + response.getException());
                                        resultEmitter.onComplete();
                                    }
                                });
                    } catch (Exception exception) {
                        Print.showToast("支付结果查询失败" + exception);
                        resultEmitter.onComplete();
                    }
                })
                        .repeatWhen(it -> it.flatMap((Function<Object, ObservableSource<?>>) o -> Observable.timer(1, TimeUnit.SECONDS)))
                        .subscribe();
    }

    @Override
    public void onChoiceChangeListener(ChoiceCard cc, IChoiceItem c, int index) {
        if (c.getIsChoice()) {
            FunItem funItem = (FunItem) c.getTag();
            float   number  = -1;
            try {
                number = Float.parseFloat(funItem.id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            handNumber(number, true);
        }

    }

    private void handNumber(float number, boolean isFinally) {

        int num = (int) number;

        if (num == OnSteelyardKeyEvent.KEYCODE_Money) {
            num = Money_keyCode;//现金支付
        } else if (num == OnSteelyardKeyEvent.KEYCODE_PAY) {
            num = Money_keyCode;//现金支付
        } else if (num == OnSteelyardKeyEvent.KEYCODE_VipCard) {
            num = Vip_keyCode;//会员支付
        } else if (num == OnSteelyardKeyEvent.KEYCODE_VipW) {
            num = WVip_keyCode;////微会员支付
        } else if (num == OnSteelyardKeyEvent.KEYCODE_DelegatePay) {
            num = Delegate_keyCode;//聚合支付
        } else if (num == vipOrScanPay_keyCode) {//进入会员刷卡模式
            return;
        }

        boolean hasItemFun = false;

        IChoiceItem[] items = mChoiceCard.getData();
        for (IChoiceItem item : items) {
            FunItem funItem = (FunItem) item.getTag();
            if (NumberHelp.toInt(funItem.id, -1) == num) {
                hasItemFun = true;
                break;
            }
        }
        if (!hasItemFun) return;


        switch (num) {
            case 0:
                RunTimeData.orderEntity.payTypeName = "扫码支付";
                go2Trace(true);
                break;
            case 9:
                closePollingResut();
                RouterUINavigation.getInstance().dismiss(this);
                break;
        }
    }

    private void go2Trace(boolean isSuccess) {
        //加装模拟支付成功
        if (RunTimeData.orderEntity != null) {
            LinkBus.sendBroadcast(new OnPayEvent(true, RunTimeData.orderEntity, null, isSuccess));
        }
        //支付成功后这里还需要想办法通知清空购物车。
        RouterUINavigation.getInstance().showVipOrderFix((BaseFragmentActivity) getActivity());
        RouterUINavigation.getInstance().dismiss(this);
    }

    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);//中断拦截
                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {//功能键就取消当前页面。
                        RouterUINavigation.getInstance().dismiss(PayFragment01.this);
                    }
                    handNumber(data.getKeyCode(), false);//监听数字按键
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    @Override
    public void onDestroy() {
        closePollingResut();
        super.onDestroy();
        // 真正退出，而不是有别人来接替// 22-05-18 三厚哥说得不要清除。只有支付成功在提示页面退出再清除见com.lkm.app_ui.ui.VipOrderFixFragment.onDestroy

        if (lastPayFragment == this) {
            VipModule vipModule = AppConst.getModuleManager().peekModule(VipModule.class);
            if (vipModule != null)
                vipModule.exitVip();
        }
    }

    private void closePollingResut() {
        if (resultEmitter != null) resultEmitter.onNext("");
        if (mResultDisposable != null) mResultDisposable.dispose();
    }
}
